package com.tangding.hprose.api.server.command.impl.user;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.common.exception.GException;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.common.utils.Utils;
import com.tangding.config.Config;
import com.tangding.hprose.api.server.command.Command;
import com.tangding.hprose.api.server.command.Response;
import com.tangding.service.dao.user.UserRepository;
import com.tangding.service.entity.user.User;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年12月2日_下午3:37:56
 *
 */
@Component
public class CreateUser implements Command {
	
	@Autowired
	UserRepository userRepository;

	@Override
	public Response exe(Object... params) throws GException {
		String uid = JacksonUtil.get(params[0], "uid", true);
		if (Strings.isNullOrEmpty(uid) && "null".equals(uid)) {
			throw new GException(ErrorConstants.ERR_ILLEGAL_REQUEST);
		}
		if (Config.godAccount.equals(uid)) {
			throw new GException(ErrorConstants.ERR_ILLEGAL_REQUEST);
		}
		
		User checkUser = userRepository.getUserByUid(uid);
		if (checkUser != null) {//已经存在用户
			throw new GException(ErrorConstants.ERR_UID_EXIST);
		}
		
		String puid = JacksonUtil.get(params[0], "cid.selectItem.key", true);
		User user = new User();
		user.setPuid(puid);
		
		String pname = JacksonUtil.get(params[0], "cid.selectItem.info", true);
		user.setPname(pname);
		
		String name = JacksonUtil.get(params[0], "name", true);
		String password = JacksonUtil.get(params[0], "password", true);
		user.setName(name);
		user.setPassword(Utils.getMD5(Utils.getMD5(password)));
		user.setCreateTime(new Date());
		user.setUid(uid);
		user.setChannelId(Utils.uuid());
		user.setAvailable(true);
		
		userRepository.addUser(user);
		
		return doResponseSucc();
	}

}
